package com.kaxiu.config.shiro;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kaxiu.persistent.entity.BasicUser;
import com.kaxiu.persistent.entity.SysPremission;
import com.kaxiu.persistent.entity.SysRole;
import com.kaxiu.service.IBasicUserService;
import com.kaxiu.service.ISysPremissionService;
import com.kaxiu.service.ISysRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: LiYang
 * @create: 2019-08-07 19:00
 * @Description:
 **/
@Service
public class UserRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    private IBasicUserService userRepository;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPremissionService premissionService;

    /**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String currentLoginMobile = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //从数据库中获取当前登录用户的详细信息
        BasicUser userInfo = userRepository.findByLogin(currentLoginMobile);
        if (null != userInfo) {
            List<SysRole> roles = roleService.getByUserId(userInfo.getId());
            for(SysRole userrole:roles){
                Long rolid = userrole.getId();//角色id
                authorizationInfo.addRole(userrole.getName());//添加角色名字
                List<SysPremission> premissions = premissionService.getByRoleId(rolid);
                for(SysPremission p:premissions){
                    //System.out.println("角色下面的权限:"+gson.toJson(p));
                    if(StringUtils.isNotEmpty(p.getPerms())){
                        authorizationInfo.addStringPermission(p.getPerms());
                    }
                }
            }
        } else {
            throw new AuthorizationException();
        }
        logger.info("###【管理-获取角色成功】[SessionId] => {}", SecurityUtils.getSubject().getSession().getId());
        return authorizationInfo;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        //UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //查出是否有此用户
        BasicUser userInfo = userRepository.findByLogin(token.getUsername());
        if (userInfo != null) {
            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
            return new SimpleAuthenticationInfo(userInfo.getMobile(), userInfo.getPassword(), getName());
        }
        return null;
    }

}
